package com.naiterui.ehp.bs.ds.modules.goods.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Preconditions;
import com.naiterui.ehp.bp.security.utils.SecurityUtils;
import com.naiterui.ehp.bp.support.exception.BaseExceptionCodes;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bs.ds.common.utils.JwtUser;
import com.naiterui.ehp.bs.ds.common.utils.PageVO;
import com.naiterui.ehp.bs.ds.common.vo.PageParamsVO;
import com.naiterui.ehp.bs.ds.modules.goods.entity.WarehouseGoods;
import com.naiterui.ehp.bs.ds.modules.goods.feign.WarehouseGoodsFeignClient;
import com.naiterui.ehp.bs.ds.modules.goods.mapper.WarehouseGoodsMapper;
import com.naiterui.ehp.bs.ds.modules.goods.service.IWarehouseGoodsService;
import com.naiterui.ehp.bs.ds.modules.goods.vo.WarehouseGoodsInventoryExcelVO;
import com.naiterui.ehp.bs.ds.modules.goods.vo.WarehouseGoodsInventoryVO;
import com.naiterui.ehp.bs.ds.modules.goods.vo.WarehouseGoodsVO;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class WarehouseGoodsServiceImpl extends ServiceImpl<WarehouseGoodsMapper, WarehouseGoods> implements IWarehouseGoodsService {

    private final WarehouseGoodsFeignClient warehouseGoodsFeignClient;

    @Override
    public PageVO<WarehouseGoodsVO> queryPage(PageParamsVO pageParamsVO, WarehouseGoodsVO warehouseGoods) {
        QueryWrapper<WarehouseGoodsVO> entityWrapper = this.buildEntityWrapper(pageParamsVO, warehouseGoods);
        Page<WarehouseGoodsVO> page = this.baseMapper.getPage(pageParamsVO.getPage(), entityWrapper);
        return PageVO.toPageVo(page);
    }

    private QueryWrapper<WarehouseGoodsVO> buildEntityWrapper(PageParamsVO pageParamsVO, WarehouseGoodsVO warehouseGoods) {

        QueryWrapper<WarehouseGoodsVO> entityWrapper = pageParamsVO.getEntityWrapper("t");
        JwtUser currentUser = SecurityUtils.getCurrentUser();
        Long warehouseId = currentUser.getWarehouseId();
        Preconditions.checkNotNull(warehouseId, "仓库ID不能为null");
        entityWrapper.eq("t.warehouse_id", warehouseId);

        String number = warehouseGoods.getNumber();
        entityWrapper.eq(StringUtils.isNotBlank(number), "t.number", number);

        String commonName = warehouseGoods.getCommonName();
        entityWrapper.eq(StringUtils.isNotBlank(commonName), "pp.common_name", commonName);

        Long pharmacologyClassificationId = warehouseGoods.getPharmacologyClassificationId();
        entityWrapper.eq(pharmacologyClassificationId != null, "t.pharmacology_classification_id", pharmacologyClassificationId);

        Integer status = warehouseGoods.getStatus();
        entityWrapper.eq(status != null, "t.status", status);

        return entityWrapper;
    }

    @Override
    public void updateInventory(MultipartFile file) throws BusinessException {
        List<WarehouseGoodsInventoryExcelVO> inventoryExcels;
        try {
            ImportParams params = new ImportParams();
            params.setNeedVerfiy(true);
            inventoryExcels = ExcelImportUtil.importExcel(file.getInputStream(), WarehouseGoodsInventoryExcelVO.class, params);
        } catch (Exception e) {
            throw new BusinessException(BaseExceptionCodes.FAILED, "Excel修改库存失败", e);
        }
        QueryWrapper<WarehouseGoods> queryWrapper = new QueryWrapper<>();
        Set<String> skuNumbers = inventoryExcels.stream().map(WarehouseGoodsInventoryExcelVO::getSkuNumber).collect(Collectors.toSet());
        JwtUser currentUser = SecurityUtils.getCurrentUser();
        Long warehouseId = currentUser.getWarehouseId();
        Preconditions.checkNotNull(warehouseId, "仓库ID不能为null");
        queryWrapper.eq("warehouse_id", warehouseId);
        queryWrapper.in("number", skuNumbers);
        List<WarehouseGoods> list = this.baseMapper.selectList(queryWrapper);
        Map<String, WarehouseGoods> warehouseGoodsMap =
            list.stream().collect(Collectors.toMap(WarehouseGoods::getNumber, Function.identity()));
        Set<WarehouseGoodsInventoryVO> warehouseGoodsInventorys = inventoryExcels.stream()
            .map(m -> {
                WarehouseGoodsInventoryVO inventory = new WarehouseGoodsInventoryVO();
                String skuNumber = m.getSkuNumber();
                WarehouseGoods warehouseGoods = warehouseGoodsMap.get(skuNumber);
                inventory.setSkuId(warehouseGoods.getSkuId());
                inventory.setQuantity(m.getQuantity());
                return inventory;
            }).collect(Collectors.toSet());

        this.warehouseGoodsFeignClient.updateInventory(warehouseId, warehouseGoodsInventorys);
    }

}
